import { memo, useEffect, useMemo, useState } from "react";
import TimetableStyle from "./style";
import { useGetTodayTimetable } from "../../../../service/timetable";
import { TimetableType } from "../../../../graphql/timetable";
import { Avatar, Descriptions, Result, Spin, Steps, Tooltip } from "antd";
import { useAsyncEffect } from "ahooks";
import { useGetTimetableRecords } from "../../../../service/timetableRecord";
import { useGetStudentInfo_simple } from "../../../../service/student";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
import { UserOutlined } from "@ant-design/icons";

dayjs.extend(isBetween);

interface IProps {
  today: string;
}

interface timetableMapStudentsType {
  timetableId: string;
  student: {
    id: string;
    name: string;
    avater: string;
  }[];
}

const Timetable = memo((props: IProps) => {
  const { today, createTimetableSuccess } = props;
  const [timetableMapStudents, setTimetableMapStudents] =
    useState<timetableMapStudentsType[]>();
  const [todayTimeTables, setTodayTimeTables] = useState<TimetableType[]>();

  const { getTodayTimetable, loading: getTimetableLoading } =
    useGetTodayTimetable();
  const { getTimetableRecords, loading: getTimetableRecordsLoading } =
    useGetTimetableRecords();
  const { getStudentInfo } = useGetStudentInfo_simple();

  // 步骤条步骤
  const stepsCurunt = useMemo(() => {
    if (todayTimeTables) {
      // 当没有符合时间的课程时
      let step = -1;
      for (let i = 0; i < todayTimeTables.length; i++) {
        const item = todayTimeTables[i];
        const startTime = dayjs(dayjs().format("YYYY-MM-DD") + item.startTime);
        const endTime = dayjs(dayjs().format("YYYY-MM-DD") + item.endTime);
        if (dayjs().isBetween(startTime, endTime)) {
          return i;
        }
        if (dayjs().isAfter(endTime)) {
          step++;
        }
      }
      return step;
    }
  }, [today, todayTimeTables]);
  useEffect(() => {
    if (today && createTimetableSuccess) {
      void getTodayTimetable(today).then((res) => {
        setTodayTimeTables(res.data);
      });
    }
  }, [today, createTimetableSuccess]);

  useAsyncEffect(async () => {
    if (todayTimeTables) {
      // 一个课程可能有多个用户预约
      const timetableRecordsArr: {
        id: string;
        studentId: string;
        timetableId: string;
      }[][] = [];
      const studentArr: timetableMapStudentsType[] = [];
      for (const timeTable of todayTimeTables) {
        const res = await getTimetableRecords(timeTable.id);
        timetableRecordsArr.push(
          // {id: 课程表记录的数据id ，timetableId： 课程表的数据id}
          res.data as { id: string; studentId: string; timetableId: string }[]
        );
      }
      for (const student of timetableRecordsArr.flat()) {
        const res = await getStudentInfo(student.studentId);
        const index = studentArr.findIndex(
          (item) => item.timetableId === student.timetableId
        );
        if (index !== -1) {
          studentArr[index].student.push({
            id: res.id,
            avater: res.avatar,
            name: res.name,
          });
        } else {
          studentArr.push({
            timetableId: student.timetableId,
            student: [
              {
                id: student.studentId,
                avater: res.avatar,
                name: res.name,
              },
            ],
          });
        }
      }
      setTimetableMapStudents(studentArr);
    }
  }, [todayTimeTables]);
  return (
    <TimetableStyle>
      {getTimetableLoading || getTimetableRecordsLoading ? (
        <Spin size="large" />
      ) : (todayTimeTables?.length ?? 0) > 0 ? (
        <Steps
          current={stepsCurunt}
          direction="vertical"
          items={todayTimeTables?.map((item) => ({
            title: `${item.startTime} - ${item.endTime} ${
              JSON.parse(item.courseId).name as string
            }`,
            description: (
              <Descriptions bordered size="small">
                <Descriptions.Item
                  span={3}
                  label={
                    <>
                      <UserOutlined /> 学员
                    </>
                  }
                  labelStyle={{ width: 70 }}
                >
                  {(timetableMapStudents?.length ?? []) > 0 ? (
                    <Avatar.Group
                      maxCount={10}
                      maxStyle={{
                        color: "#f56a00",
                        backgroundColor: "#fde3cf",
                      }}
                    >
                      {timetableMapStudents
                        ?.find((i) => i.timetableId === item.id)
                        ?.student.map((stu) => (
                          <Tooltip
                            title={stu.name}
                            placement="top"
                            key={stu.id}
                          >
                            <Avatar src={stu.avater} />
                          </Tooltip>
                        ))}
                    </Avatar.Group>
                  ) : (
                    "该课程暂无学员预约"
                  )}
                </Descriptions.Item>
              </Descriptions>
            ),
          }))}
        />
      ) : (
        <Result status="404" subTitle="该日期暂无排课" />
      )}
    </TimetableStyle>
  );
});

export default Timetable;
